#!/bin/sh
#
# Build Applications from scratch (with GPL v2).
#
# Authors: 
#	Conke   <conke.hu@gmail.com>
# 	Linke   <linke.wang@gmail.com>
#


IMAGE_PREFIX=rootfs
BAK_RUNTIME_LIB=.rootfs_lib
BAK_DEVELOP_LIB=.rootfs_usr_lib

echo
echo "Creating rootfs images:"

mkdir -p ${ROOTFS_PATH}/../images
cd ${ROOTFS_PATH}/../images
OUTPUT_PATH=`pwd`
rm -f rootfs*.img

#save lib and usr/lib directory
cp -a ${ROOTFS_PATH}/lib ${OUTPUT_PATH}/${BAK_RUNTIME_LIB}
cp -a ${ROOTFS_PATH}/usr/lib ${OUTPUT_PATH}/${BAK_DEVELOP_LIB}

#strip lib
${SYSROOT_PATH}/usr/bin/${TARGET_PLAT}-strip ${ROOTFS_PATH}/lib/* > /dev/null 2>&1
${SYSROOT_PATH}/usr/bin/${TARGET_PLAT}-strip ${ROOTFS_PATH}/usr/lib/* > /dev/null 2>&1

for imgtool in mkyaffsimage mkyaffs2image mkfs.jffs2 mkfs.cramfs cpio;
do
	TOOL_PATH=`which ${imgtool}`
	case "$TOOL_PATH" in
	*mkyaffsimage)
		echo "yaffs1 image (${OUTPUT_PATH}/${IMAGE_PREFIX}.yaffs1) ... "
		${TOOL_PATH} ${ROOTFS_PATH} ${OUTPUT_PATH}/${IMAGE_PREFIX}.yaffs1 > /dev/null
		chmod 0644 ${OUTPUT_PATH}/${IMAGE_PREFIX}.yaffs1
		;;	
	*mkyaffs2image)
		echo -n "yaffs2 image (${OUTPUT_PATH}/${IMAGE_PREFIX}.yaffs2) ... "
		${TOOL_PATH} ${ROOTFS_PATH} ${OUTPUT_PATH}/${IMAGE_PREFIX}.yaffs2 > /dev/null
		chmod 0644 ${OUTPUT_PATH}/${IMAGE_PREFIX}.yaffs2
		;;
	*mkfs.jffs2)
		echo "\njffs2 image (${OUTPUT_PATH}/${IMAGE_PREFIX}.jffs2) ... "
		${TOOL_PATH} -r ${ROOTFS_PATH} -s 512 -e 0x4000 -l -p -n -o ${OUTPUT_PATH}/${IMAGE_PREFIX}_s.jffs2
		${TOOL_PATH} -r ${ROOTFS_PATH} -s 2048 -e 0x20000 -l -p -n -o ${OUTPUT_PATH}/${IMAGE_PREFIX}_l.jffs2
		;;	
	*mkfs.cramfs)
		echo "cramfs image (${OUTPUT_PATH}/${IMAGE_PREFIX}.cramfs) ... "
		${TOOL_PATH} -b 512 ${ROOTFS_PATH} ${OUTPUT_PATH}/${IMAGE_PREFIX}.cramfs
		;;
	*cpio)
		echo "ramdisk image (${OUTPUT_PATH}/${IMAGE_PREFIX}.rd) ..."
		cd ${ROOTFS_PATH} && find | ${TOOL_PATH} -o -H newc 2> /dev/null | gzip -9 > ${OUTPUT_PATH}/${IMAGE_PREFIX}.rd
		;;
	*)
		echo "${imgtool} not found, skipping"
		;;
	esac
done

#restore lib and usr/lib directory
rm -rf ${ROOTFS_PATH}/lib
mv ${OUTPUT_PATH}/${BAK_RUNTIME_LIB} ${ROOTFS_PATH}/lib

rm -rf ${ROOTFS_PATH}/usr/lib
mv ${OUTPUT_PATH}/${BAK_DEVELOP_LIB} ${ROOTFS_PATH}/usr/lib

echo
TREE=`which tree`
if [ x"${TREE}" != x"" ]; then
	echo
	echo "${ROOTFS_PATH} :"
	cd ${ROOTFS_PATH}
	${TREE} -d -L 2 
	echo
fi

